import Taro, { switchTab, setNavigationBarTitle, setNavigationBarColor, useDidShow } from '@tarojs/taro'
import { View, Image, Button, Navigator, Form, Input } from '@tarojs/components'
import { AtIcon, AtButton, AtForm, AtInput } from 'taro-ui'
import React, { useState, useEffect } from 'react'

import api, { getCaptcha, doLogin } from '../../utils/api'
import request from '../../utils/request'
import { useAsyncEffect } from '../../utils/index'

import IconUser from '../../images/icon-user.png'
import IconPassword from '../../images/icon-password.png'
import IconCaptcha from '../../images/icon-captcha.png'

import './login.less'


function Login() {
  useDidShow(() => {
    setNavigationBarTitle({
      title: '用户登录'
    })
    setNavigationBarColor({
      backgroundColor: '#f8f8f8',
      frontColor: '#000000'
    })
  })
  useEffect(() => {
    getCaptchaPic()
  }, [])

  const [captchaKey, setCapToken] = useState('')
  const [codeurl, setCodeUrl] = useState('')
  const [username, setUserName] = useState('')
  const [password, setPassword] = useState('')
  const [captcha, setCaptcha] = useState('')

  const handleUserNameChange = (value) => {
    setUserName(value)
  }
  const handlePasswordChange = (value) => {
    setPassword(value)
  }
  const handleCodeChange = (value) => {
    setCaptcha(value)
  }

  const getCaptchaPic = async () => {
    try {
      const data = await request(getCaptcha)
      setCapToken(data.verifykey)
      setCodeUrl(data.img)
      setCaptcha('')
    } catch (error) {
      console.log(error)
      Taro.showToast({
        title: '载入远程数据错误',
        icon: 'none'
      })
    }
  }
  const onSubmitFrom = (e) => {
    Taro.login().then(res => {
      if (res.code) {
        let data = {
          captchaKey,
          ...e.detail.value,
          js_code: res.code
        }
        request(doLogin, 'POST', data).then((data) => {
          data.info.username = data.username
          Taro.setStorage({
            key: 'loginInfo',
            data: data.info
          })
          Taro.setStorage({
            key: 'token',
            data: data.token
          })
          switchTab({
            url: '/pages/mine/mine'
          })
        }).catch(err => {
          getCaptchaPic()
        })
      } else {
        getCaptchaPic()
        Taro.showToast({
          title: '登录失败！' + res.errMsg,
          icon: 'none'
        })
      }
    })
  }
  return (
    <View className='login'>
      <View className='group'>
        <Form className="form" onSubmit={onSubmitFrom}>
          <View className="form-item">
            <Image mode='aspectFill' className='icon' src={IconUser} />
            <View className="input">
              <Input name='username' type='text' placeholder='请输入登录账号'></Input>
            </View>
          </View>
          <View className="form-item">
            <Image mode='aspectFill' className='icon' src={IconPassword} />
            <View className="input">
              <Input name='password' type='password' placeholder='请输入登录密码'></Input>
            </View>
          </View>
          <View className="form-item">
            <Image mode='aspectFit' className='icon' src={IconCaptcha} />
            <View className="input">
              <Input name='captcha' type='text' value={captcha} className="input" placeholder='验证码'></Input>
              <View className="right">
                <Image className="right-val" onClick={getCaptchaPic} src={codeurl} />
              </View>
            </View>
          </View>
          <Navigator url="/pages/forget/forget" className="forget">初始化密码</Navigator>
          <Button className="form-button" formType="submit">登 录</Button>
        </Form>
      </View>
    </View>
  )
}

export default Login
